
import React,{useCallback,useState, useMemo} from 'react'



//此时父组件更新子组件也会更新 
// memo是比对属性是否更新决定重新渲染，相当于备忘录一样
function child({data,handleClick}){
  return <button onclick={handleClick}>{data.number}</button>
}
function App(){
const [name,setName] =useState('')
const [number,setNumber] =useState(0)
const data ={number}

const handleClick=()=>{
  setNumber(number+1)
}
return(
  <div>
    <input type="text" value={name} onChange={(event)=>setName(event.target.value)}/>
    <child  data={data} handleClick={handleClick}/>
  </div>
)
}

// 子组件加上react.memo，但是子组件还是更新了
// 原因：每次渲染父组件时，data和handleClick重新生成一个新的对象、函数
function child({data,handleClick}){
  return <button onclick={handleClick}>{data.number}</button>
}
let childWithMemo =React.memo(child)

function App(){
const [name,setName] =useState('')
const [number,setNumber] =useState(0)
const data ={number}

const handleClick=()=>{
  setNumber(number+1)
}
return(
  <div>
    <input type="text" value={name} onChange={(event)=>setName(event.target.value)}/>
    <childWithMemo  data={data} handleClick={handleClick}/>
  </div>
)
}

// 子组件不更新了
function child({data,handleClick}){
  return <button onclick={handleClick}>{data.number}</button>
}
let childWithMemo =React.memo(child)

function App(){
const [name,setName] =useState('')
const [number,setNumber] =useState(0)
const data =useMemo(()=>({number}),number)

const handleClick=useCallback(()=>{
  setNumber(number+1)
},[number])
return(
  <div>
    <input type="text" value={name} onChange={(event)=>setName(event.target.value)}/>
    <childWithMemo  data={data} handleClick={handleClick}/>
  </div>
)
}